import {addressAdd,addressGet} from '../api/user'
export default {
  namespaced:true,
  state(){
    return {
      addressList:[
        // {
        //   username:'张三丰',
        //   phone:'13955556666',
        //   tel:['023','12345678'],
        //   loc:[
        //     {name:'河北',idx:2},
        //     {name:'石家庄',idx:0},
        //     {name:'桥东区',idx:1},
        //   ],
        //   address:'桥头老地方',
        //   isdefault:true,
         //  userid:用户的_id
        // },
        // {
        //   username:'无忌',
        //   phone:'13955557777',
        //   tel:['023','55665678'],
        //   loc:[
        //     {name:'山西',idx:3},
        //     {name:'大同',idx:1},
        //     {name:'矿区',idx:1}
        //   ],
        //   address:'1号井30眼',
        //   isdefault:false
        // }
      ],
      checkIdx:-1 //用户点选的地址下标
    }
  },
  getters:{
    addressIdx(state){
      let {addressList,checkIdx} = state
      let len = addressList.length
      //初始化的勾选下标
      if(checkIdx==-1){
        for(let i=0;i<len;i++){
          if(addressList[i].isdefault){
            return i
          }
        }
      }
      //用户点击后选中的下标
      return checkIdx 
    }
  },
  mutations:{
    addressAddMut(state,addressObj){ //新增地址
      state.addressList.push(addressObj)
    },
    addressCheckMut(state,idx){  //地址勾选
      state.checkIdx = idx
    },
    addressInitMut(state,addressList){ //初始化收货地址
      state.addressList = addressList
    }
  },
  actions:{ //状态机中，只能在actions里面发异步请求
    addressAddAct(context,addressObj){ //context等同于store对象，可以操作状态机的state、getters、mutations
      addressAdd(addressObj).then(res=>{
        // console.log(res);
        context.commit('addressAddMut',res.data)
      })
    },
    addressInitAct(context,userid){ //加载收货地址的异步action
      addressGet().then(res=>{
        console.log(res);
        context.commit('addressInitMut',res.data)
      })
    }
  }
}